package controllers;

import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.JOptionPane;


import models.CustomerModel;
import dialogs.DeleteTupleDialog;
import dialogs.InsertTupleDialog;

import system.View;

public class CustomerController extends AbstractMenuItemController {
	private CustomerModel customer = new CustomerModel();

	public CustomerController(View v) {
		super(v);
		abstractModel = customer;
		customer.addExceptionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();

		if (actionCommand.equals("Delete Customer"))
			showDialogWindow(new DeleteTupleDialog(view, actionCommand, "Key",
					new String[] { "Customer ID Number: " }, this));
		else if (actionCommand.equals("Insert Customer"))
			showDialogWindow(new InsertTupleDialog(view, actionCommand,
					"Customer", new String[] { "Customer ID", "Customer Password: ", "Name: ",
							"Address: ", "Phone Number: " }, this));
	}

	@Override
	public int validateInsert(Vector<String> s) {
		if(s.size() != 5) return VALIDATIONERROR;
		
		try 
		{	
			String cid;
			String password;
			String name;
			String address;
			String phone;
			
			if(s.get(0).trim().length() != 0)
				cid = s.get(0).trim();
			else return VALIDATIONERROR;
			if(s.get(1).trim().length() != 0)
				password = s.get(1).trim();
			else return VALIDATIONERROR;
			if(s.get(2).length() != 0)
				name = s.get(2).trim();
			else return VALIDATIONERROR;
			if(s.get(3).length() != 0)
				address = s.get(3).trim();			
			else return VALIDATIONERROR;
			if(s.get(4).length() != 0)
				phone = s.get(4).trim();
			else return VALIDATIONERROR;
			
			view.updateStatusBar("Inserting Customer...");

			if ( customer.insert(cid, password, name, address, phone) ) return operationSuccess();
			else
			{
				return operationFailure(); 
			}
		}  catch (NumberFormatException ex) { return VALIDATIONERROR; }
	}

	@Override
	public int validateDelete(Vector<String> s) {
		if (s.size() != 1)
			return VALIDATIONERROR;

		try {
			String cid;

			if (s.get(0).trim().length() != 0) {
				cid = s.get(0).trim();
			} else
				return VALIDATIONERROR;

			view.updateStatusBar("Deleting Customer...");

			if (customer.delete(cid))
				return operationSuccess();
			else
				return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}
}